package com.credit.mola.app.ui.launch

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.credit.mola.app.analysis.TestAnalysisInit
import com.credit.mola.app.databinding.ActivityLaunchBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.ui.credit.activity.CreditActivity
import com.credit.mola.app.ui.user.activity.UserLoginActivity
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.VersionUpdateDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.helper.ActivityStackHelper
import com.credit.mola.app.utils.helper.CmVersionUpdateHelper
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.IHttpCallback
import org.json.JSONObject
import java.util.TimeZone

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 16:12
 * @Annotation：启动页
 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity: ProActivity() {
    private lateinit var binding: ActivityLaunchBinding
    private var updateHelper: CmVersionUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            showEnterPage()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (updateHelper == null) {
                showEnterPage()
                return@registerForActivityResult
            }
            updateHelper?.haveNoUpdateCallback {
                showEnterPage()
            }
        }
    }

    override fun getRootView(): View {
        binding = ActivityLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        isNeedHideLoading = false
        //关闭所有页面
        ActivityStackHelper.finishAllActivity(LaunchActivity::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        Configs.saveSPInt(Configs.SPKEY.CREDIT_MOLA_NOTICE_SHOW_NUM,0)
    }

    override fun initListener() {

    }

    override fun initData() {
        showLoading()
        loadTimeZoneAction()
    }

    private fun showEnterPage(){
        //已登录 - 进入主页
        if (Configs.getSPBoolean(Configs.SPKEY.SIKADWA_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            TestAnalysisInit.initAnalysisLibAtLoginSuccess()
            enterMainPage()
        } else {//进入登录页
            enterLoginPage()
        }
    }

    /**
     * 进入登录
     */
    private fun enterLoginPage() {
        onIntent(UserLoginActivity::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    private fun enterMainPage() {
        //保存过时区 && 时区不相同 需要重新登录
        val saveZoneId = Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_ID)
        if (saveZoneId.isNotEmpty() && saveZoneId != TimeZone.getDefault().id){
            enterLoginPage()
            return
        }
        onIntent(CreditActivity::class.java)
        finish()
    }

    /**
     * 版本更新Dialog
     */
    private fun showCmVersionUpdateDialog(){
        val versionUpdateDialog = VersionUpdateDialog(this,"Launch page",object : VersionUpdateDialog.IDialogCallback{
            override fun onUpdateNowClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = CmVersionUpdateHelper(this@LaunchActivity, true, updateLauncher)
                    }
                    updateHelper?.checkVersionUpdate { showEnterPage() }
                } catch (e: Exception) {
                    showEnterPage()
                }
            }
        })
        versionUpdateDialog.show()
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.onResumeInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LAUNCH_END,"")
    }

    /**
     * 获取地区转发
     * Timezone
     */
    private fun loadTimeZoneAction(){
        val params = JSONObject().apply {
            put("p",Configs.AppName)
            put("tz", TimeZone.getDefault().id)
        }
        val httpUrl = AppUrls.APP_URL + AppUrls.URL.TIMEZONE
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val dataString = data.optString("data")
                var timeZone = ""
                var zoneCode = ""
                var zoneCountry = ""

                dataString.split(",").apply {
                    if (this.isNotEmpty()){
                        timeZone = this[0].trim()
                    }
                    if (this.size >= 2){
                        zoneCode = this[1].trim()
                    }
                    if (this.size >= 3){
                        zoneCountry = this[2].trim()
                    }
                }
                //保存转发地区
                Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE,timeZone)
                //保存转发地区 区号
                Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE,zoneCode)
                //保存国家标识
                Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_COUNTRY,zoneCountry)
                //初始化analysis lib 赋值 转发地区
                TestAnalysisInit.initAnalysisLibAtZoneSuccess()
                addEvent(EventType.PAGE.PAGE_LAUNCH_START,"")

                loadConfigAction()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }

        })
    }

    /**
     * 获取APP配置信息
     */
    private fun loadConfigAction(){
        val params = JSONObject().apply {
            put("product",Configs.AppName)
            put("path",AppUrls.PATH.APP_INFO)
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                hideLoading()
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
                    // 测试模拟版本更新
//                    val customize = obj.optJSONObject("customize")
//                    val customData = customize.optJSONObject("customData")
//                    val testVersion = JSONObject()
//                    testVersion.put("isMustUpdate",false)
//                    testVersion.put("versionCode","4")
//                    testVersion.put("versionName","1.0.4")
//                    testVersion.put("versionRemark","Um novo design de interface de utilizador.\$Atualizar processamento de dados mais seguro.\$Resolva bugs conhecidos, otimize o código e melhore a experiência do utilizador.")
//                    customData.put("release",testVersion)
                    CustomConfigHelper.saveCustomConfigData(obj.toString())
                }
                //强制更新
                if (CustomConfigHelper.isCmVersionUpdateMust()){
                    showCmVersionUpdateDialog()
                    return
                }
                showEnterPage()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }
}